import { action, observable } from 'mobx';
import { listOrgByParentId, saveOrg, listOrgType, deleteOrg, listOrgByName } from '../service';
import loading from '../../../components/Loading';
import { message } from 'antd';

class AppStore {

  // 机构抽屉参数
  @observable orgDrawerData = {
    loading: false,
    visible: false,
    editData: {},
  };

  // 机构列表参数
  @observable orgListData = {
    dataSource: [],
    loading: false,
    pageSize: 10,
    pageNo: 1,
  };

  // 机构类型字典
  @observable orgType = [];


  /**
   * 析构函数
   */
  constructor() {
    this.initData();
  }

  /**
   * 初始化页面，加载数据
   * @returns {Promise<void>}
   */
  async initData() {
    this.orgType = await listOrgType();
    this.listOrgByName();
  }

  /**
   * 新增或者修改组织机构
   * @param record 组织机构
   */
  async showOrgDrawer(record) {
    this.orgDrawerData = { ...this.orgDrawerData, editData: record, visible: true };
  }

  /**
   * 关闭组织机构抽屉
   */
  @action
  closeOrgDrawer() {
    this.orgDrawerData = { ...this.orgDrawerData, visible: false };
  };

  /**
   * 保存机构数据，并关闭对话框
   * @param org
   * @returns {Promise<void>}
   */
  @action
  async saveOrg(org) {
    await loading(saveOrg, this.orgDrawerData)(org);
    await this.listOrgByName();
    message.success('保存组织机构信息成功！');
    this.closeOrgDrawer();
  };

  /**
   * 删除机构响应函数
   * @param record 机构记录
   */
  async deleteOrg(record) {
    let result = await deleteOrg(record);
    if (result.code == 0) {
      this.listOrgByName();
      message.success('删除机构成功！');
    } else {
      message.error(result.msg);
    }

  };

  @action
  async paginationListOrg(pageNo, pageSize) {
    this.orgListData = { ...this.orgListData, pageNo: pageNo, pageSize: pageSize };
    this.listOrgByName();
  }

  async listOrgByName() {
    const p = await loading(listOrgByName, this.orgListData)(this.orgListData.pageNo, this.orgListData.pageSize, this.type, this.name);
    this.orgListData.dataSource = p.rows;
    this.orgListData.pageNo = p.pageNo;
    this.orgListData.total = p.total;
  }

  /**
   * 根据机构名称模糊查询机构列表
   * @param name 机构名称
   */
  async searchOrg(type, name) {
    this.name = name;
    this.type = type;
    this.listOrgByName();
  }
}

export default AppStore;
